const jwt = require("jsonwebtoken");
const db = require("../../config/db");
require("dotenv").config();

const SECRET_KEY = process.env.JWT_SECRET || "my_secret_key";

// 📌 管理员登录
exports.loginAdmin = async (req, res) => {
  const { username, password } = req.body;

  try {
    const [rows] = await db.query("SELECT * FROM admins WHERE username = ?", [username]);

    if (rows.length === 0) {
      return res.status(401).json({ message: "用户名不存在" });
    }

    const admin = rows[0];
    if (admin.password !== password) {
      return res.status(401).json({ message: "密码错误" });
    }

    const token = jwt.sign({ id: admin.id, username: admin.username }, SECRET_KEY, { expiresIn: "2h" });

    res.json({ message: "登录成功", token });
  } catch (err) {
    console.error("❌ 登录失败:", err);
    res.status(500).json({ message: "服务器错误" });
  }
};

// 📌 获取管理员列表（可选功能）
//exports.getAdmins = async (req, res) => {
//  try {
//    const [rows] = await db.query("SELECT id, username FROM admins");
//    res.json(rows);
//  } catch (err) {
//    res.status(500).json({ message: "获取管理员列表失败" });
//  }
//};
